package com.ldxx.mustwinlottery.model.impl;

import com.ldxx.mustwinlottery.base.BaseModel;
import com.ldxx.mustwinlottery.base.IBaseRequestCallBack;
import com.ldxx.mustwinlottery.base.ResultBean;
import com.ldxx.mustwinlottery.model.IssueModel;
import com.ldxx.mustwinlottery.model.bean.IssueBean;
import com.ldxx.mustwinlottery.service.IssueService;

import java.util.List;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 *
 * Created by ldxx on 16/8/29.
 */

public class IssueModelImpl extends BaseModel implements IssueModel {
    //private static final String TAG = "IssueModelImpl";
    private IssueService service;

    public IssueModelImpl() {
        service = retrofitManager.getService(IssueService.class);
    }

    @Override
    public void getIssueInfos(final IBaseRequestCallBack<List<IssueBean>> callBack) {
      HttpResultFunc<List<IssueBean>> hrf =  new HttpResultFunc<>();
        service.getCurrentIssue()
                .map(hrf)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<IssueBean>>() {
                    @Override
                    public void onCompleted() {
                        callBack.requestComplete();
                    }

                    @Override
                    public void onError(Throwable e) {
                        callBack.requestError(e);
                    }

                    @Override
                    public void onNext(List<IssueBean> bean) {
                        if (bean == null) {
                            callBack.requestError(new Exception("null"));
                        } else {
                            callBack.requestSuccess(bean);
                        }
                    }
                });
    }

    private class HttpResultFunc<T> implements Func1<ResultBean<T>, T> {

        @Override
        public T call(ResultBean<T> httpResult) {
            if (httpResult.getErrorNum() == 0) {
                return null;
            }
            return httpResult.getData();
        }

    }

}
